<?php

namespace Fluency;

/**
 * Represents a HTTP response. Consists of a request body and an array of headers.
 *
 * Note that instances of this class are immutable, so its mutator methods (e.g. `withHeader()`)
 * actually return a new (cloned) instance.
 *
 * @package Fluency
 * @author  Ignas Rudaitis
 * @version 2.0.0
 */
class Response
{
    private $body;
    private $headers;

    /**
     * The constructor.
     *
     * @param string $body the response body
     * @param string[] $headers HTTP headers
     */
    public function __construct($body = "", array $headers = array())
    {
        $this->body = $body;
        $this->headers = $headers;
    }

    /**
     * Gets the response body.
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Gets all HTTP headers assigned to the response.
     *
     * @return string[]
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * Sends all HTTP headers assigned to the response.
     *
     * @return Fluency\Response $this
     */
    public function sendHeaders()
    {
        foreach ($this->getHeaders() as $header) {
            header($header);
        }
        return $this;
    } 

    /**
     * Returns the string representation of the response, which is the response body.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getBody();
    }

    /**
     * Returns a clone of the current instance with the response body set to the given value.
     *
     * @param string $body
     * @return Fluency\Response
     */
    public function withBody($body)
    {
        $clone = clone $this;
        $clone->body = $body;
        return $clone;
    }

   /**
     * Returns a clone of the current instance with the given HTTP header appended to the header
     * list.
     *
     * @param string $header
     * @return Fluency\Response
     */
    public function withHeader($header)
    {
        $clone = clone $this;
        $clone->header = $header;
        return $clone;
    }

    /**
     * Returns a clone of the current instance with the header list replaced with the given array.
     *
     * @param string[] $headers
     * @return Fluency\Response
     */
    public function withHeaders(array $headers)
    {
        $clone = clone $this;
        $clone->headers = $headers;
        return $clone;
    }
}
